package dao;

import dao.inte.TemplateRepository;
import domain.Template;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Singleton;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.logging.Logger;

@Singleton
@Transactional
public class TemplateRepositoryImpl extends AbstractEntityRepository<Template> implements TemplateRepository {
    public TemplateRepositoryImpl() {
        super(Template.class);
    }

    private final static Logger logger = Logger.getLogger(TemplateRepositoryImpl.class.getName());


    @Override
    protected Class<Template> getEntityClass() {
        return Template.class;
    }

    @Transactional(noRollbackFor = NoResultException.class)
    public Template findByKey(String key) throws Exception {
        Query q = entityManager.createQuery("from Template u where u.key = :key");
        q.setParameter("key", key);

        Template template;
        try {
            template = (Template) q.getSingleResult();
        } catch (NoResultException e) {
            template = new Template(key, "foo");
            save(template);
        }
        return template;
    }

}